/****************************************
File name: Manip.c
Author: Gu Zhengxiong
Version: 2013.11.22
Description:The file implements functions in MANIP.
****************************************/

# include <stdlib.h>
# include <stdio.h>
# include <string.h>

# include "StudentInfo.h"
# include "StudentGrade.h"
# include "Student.h"
# include "Manip.h"

static PSTUDENT
Construct (void)
{
	PSTUDENT ps = (PSTUDENT)malloc (sizeof (STUDENT));
	ps->pnext = NULL;
	return ps;
}
static void
Add (PSTUDENT phead, PINFO pi_in, PGRADE pg_in)
{
	PSTUDENT ps = (PSTUDENT)malloc (sizeof (STUDENT));
	PSTUDENT ps_tmp = phead;
	ps->pi = pi_in;
	ps->pg = pg_in;
	ps->Display = Display;
	ps->DestroyPs = DestroyPs;
	while (ps_tmp->pnext != NULL)
		ps_tmp = ps_tmp->pnext;
	ps_tmp->pnext = ps;
	ps->pnext = NULL;
}
static void
DisplayInfo (PSTUDENT phead)
{
	PSTUDENT ps_tmp = phead;
	while (ps_tmp != NULL)
	{
		if (ps_tmp == phead)
			;
		else
		{
			printf (ALL_INFO_FORMAT, ALL_INFO_PARA);
		}
			ps_tmp = ps_tmp->pnext;
	}
}
static void
DisplayGrade (PSTUDENT phead)
{
	PSTUDENT ps_tmp = phead;
	while (ps_tmp != NULL)
	{
		if (ps_tmp == phead)
			;
		else
		{
			printf (ALL_GRADE_FORMAT, ALL_GRADE_PARA);
		}
			ps_tmp = ps_tmp->pnext;
	}
}
static PSTUDENT
Inquire (PSTUDENT phead, int type, char * s)
{
	PSTUDENT ps_tmp = phead;
	while (ps_tmp != NULL)
	{
		if (ps_tmp == phead)
			;
		else
		{
			switch (type)
			{
				case SEARCH_NUM: 
								if (strcmp (s, ps_tmp->pi->number) == 0)
									return ps_tmp;
								break;
				case SEARCH_NAME:
								if (strcmp (s, ps_tmp->pi->name) == 0)
									return ps_tmp;
								break;
			}
		}
		ps_tmp = ps_tmp->pnext;
	}
	return NULL;
}
static PSTUDENT
InquireBefore (PSTUDENT phead, int type, char * s)
{
	PSTUDENT ps_tmp = phead;
	while (ps_tmp->pnext != NULL)
	{
		switch (type)
		{
			case SEARCH_NUM: 
							if (strcmp (s, ps_tmp->pnext->pi->number) == 0)
								return ps_tmp;
							break;
			case SEARCH_NAME:
							if (strcmp (s, ps_tmp->pnext->pi->name) == 0)
								return ps_tmp;
							break;
		}
	ps_tmp = ps_tmp->pnext;
	}
	return NULL;
}
static void
Destroy (PSTUDENT phead)
{
	PSTUDENT ps_tmp = phead;
	while (ps_tmp != NULL)
	{
		if (ps_tmp == phead)
			;
		else
		{	free (ps_tmp->pg);
			free (ps_tmp->pi);
		}
		ps_tmp = ps_tmp->pnext;
	}
}
PMANIP
ManipInitialize (void)
{
	PMANIP pm = (PMANIP)malloc (sizeof (MANIP));
	pm->Construct = Construct;
	pm->Add = Add;
	pm->Inquire = Inquire;
	pm->InquireBefore = InquireBefore;
	pm->DisplayInfo = DisplayInfo;
	pm->DisplayGrade = DisplayGrade;
	pm->Destroy = Destroy;

	return pm;
}